package com.example.customer01.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.customer01.mapper.AdminMapper;
import com.example.customer01.pojo.Admin;
import com.example.customer01.service.AdminService;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import org.springframework.util.DigestUtils;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public Admin login(String username, String password) {
        // 使用MD5加密密碼
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        
        // 查詢管理員
        return lambdaQuery()
                .eq(Admin::getUsername, username)
                .eq(Admin::getPassword, encryptedPassword)
                .one();
    }

    @Override
    public boolean register(Admin admin) {
        // 檢查用戶名是否已存在
        if (checkUsernameExists(admin.getUsername())) {
            return false;
        }
        
        // 設置創建時間
        admin.setCreatedAt(LocalDateTime.now());
        
        // 使用MD5加密密碼
        String encryptedPassword = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(encryptedPassword);
        
        // 如果沒有設置角色，設置默認角色
        if (admin.getRole() == null) {
            admin.setRole("admin");
        }
        
        // 插入管理員記錄
        return save(admin);
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return lambdaQuery()
                .eq(Admin::getUsername, username)
                .exists();
    }

    @Override
    public boolean updatePassword(Integer adminId, String oldPassword, String newPassword) {
        // 獲取管理員信息
        Admin admin = getById(adminId);
        if (admin == null) {
            return false;
        }

        // 驗證舊密碼
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!admin.getPassword().equals(encryptedOldPassword)) {
            return false;
        }

        // 更新新密碼
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        admin.setPassword(encryptedNewPassword);
        
        return updateById(admin);
    }
} 